package reone.android.anytest.MyMovieRecorderTest.view;

import android.content.Context;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Environment;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.VideoView;

import java.io.File;
import java.io.IOException;

import reone.android.anytest.AppContacts;
import reone.android.anytest.Util.LogUtil;

/**
 * 视频播放控件
 *
 * @date 2015-2-5
 */
public class MyMovieRecorderView extends LinearLayout implements SurfaceHolder.Callback {


    private VideoView mVideoView;
    private String mVideoFileAbPath;
    private static String suffix = ".mp4";
    private Camera mCamera;
    private String TAG = "MyMovieRecorderView";
    private MediaRecorder record;


    public MyMovieRecorderView(Context context) {
        this(context, null);
    }

    public MyMovieRecorderView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyMovieRecorderView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mVideoFileAbPath = Environment.getExternalStorageDirectory() + "/" + AppContacts.DEFAUT_PATH + "/video/";
        mVideoView = new VideoView(getContext());
        LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        addView(mVideoView,params);
        final SurfaceHolder holder = mVideoView.getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }
    private String getAllPath(String name){
        return mVideoFileAbPath+name+suffix;
    }

    public void stopPlayVideo() {
        try {
            stopPlayingRecording();
        } catch (Exception e) {
            LogUtil.out(TAG, e.toString());
            e.printStackTrace();
        }
    }

    public void startPlayVideo(String tempVideoName) {
        try{
            playRecording(getAllPath(tempVideoName));
        }catch(Exception e){
            LogUtil.out(TAG, e.toString());
            e.printStackTrace();
        }
    }

    public void stopRecorder() {
        try{
            stopRecording();
        }catch(Exception e){
            LogUtil.out(TAG, e.toString());
            e.printStackTrace();
        }
    }

    public void startRecorder(String tempVideoName) {
        try{
            beginRecording(mVideoView.getHolder(),getAllPath(tempVideoName));
        }catch(Exception e){
            LogUtil.out(TAG, e.toString());
            e.printStackTrace();
        }
    }



    protected void beginRecording(SurfaceHolder holder, String path) throws Exception{
        // TODO Auto-generated method stub
        LogUtil.out(TAG, "beginRecording record = " + record);
        if(record != null){
            record.stop();
            record.release();
        }

        File outFile = new File(path);
        if(outFile.exists()){
            outFile.delete();
        }

        try{
            initCamera(holder);
            record = new MediaRecorder();
            record.setCamera(mCamera);
            record.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            record.setAudioSource(MediaRecorder.AudioSource.MIC);
            record.setOrientationHint(90);
            CamcorderProfile profile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
            record.setProfile(profile);
            record.setPreviewDisplay(holder.getSurface());
            record.setOutputFile(path);
            record.prepare();
            record.start();
        }catch(Exception e){
            LogUtil.out(TAG, e.toString());
            e.printStackTrace();
        }
    }

    protected void stopRecording() {
        // TODO Auto-generated method stub
        LogUtil.out(TAG, " stopRecording record = " + record);
        if(record != null){
            record.stop();
            record.release();
            record = null;
        }
        freeCameraResource();
    }

    protected void playRecording(String path) {
        // TODO Auto-generated method stub
        LogUtil.out(TAG, " playRecording");
        MediaController mc = new MediaController(getContext());
        mVideoView.setMediaController(mc);
        mVideoView.setVideoPath(path);
        mVideoView.start();
    }

    protected void stopPlayingRecording() throws Exception{
        LogUtil.out(TAG, " stopPlayingRecording ");
        // TODO Auto-generated method stub
        mVideoView.stopPlayback();
    }

    private void initCamera(SurfaceHolder holder) throws IOException {
        if (mCamera != null) {
            freeCameraResource();
        }
        try {
            mCamera = Camera.open();
        } catch (Exception e) {
            e.printStackTrace();
            freeCameraResource();
        }
        if (mCamera == null)
            return;

        if (mCamera != null) {
            Camera.Parameters params = mCamera.getParameters();
            params.set("orientation", "portrait");
            mCamera.setParameters(params);
        }
        mCamera.setDisplayOrientation(90);
        mCamera.setPreviewDisplay(holder);
        mCamera.autoFocus(new Camera.AutoFocusCallback() {
            @Override
            public void onAutoFocus(boolean success, Camera camera) {
                mCamera.cancelAutoFocus();
            }
        });
        mCamera.startPreview();
        mCamera.unlock();
    }
    private void freeCameraResource() {
        if (mCamera != null) {
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();
            mCamera.lock();
            mCamera.release();
            mCamera = null;
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }
}